package com.zhangmeng.tools.controller;


import com.zhangmeng.tools.utils.AlertUtils;
import com.zhangmeng.tools.utils.ImagePath;
import javafx.beans.property.SimpleObjectProperty;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

/**
 * @author : 芊芊墨客
 * @version : 1.0
 * @date : 2023-03-28 09:19
 */
@Slf4j
public class JSONViewController {

    @FXML
    public TextArea json_str;

    @FXML
    public Button choose_file;

    @FXML
    public Button cover;

    @FXML
    public TextField path;

    @FXML
    private TreeView<String> json_view;

    @FXML
    private SimpleObjectProperty<JSONObject> obj = new SimpleObjectProperty<>();

    @FXML
    public void initialize() {

        choose_file.setText(null);
        ImageView iv = new ImageView(new Image(ImagePath.path(ImagePath.ImagePathType.IMAGE_FILE)));
        iv.setPreserveRatio(true);
        iv.setFitWidth(18);
        choose_file.setGraphic(iv);

        choose_file.setOnAction(event -> {
            choose_file();
        });

        cover.setOnAction(event -> {

           if (json_str.getText().length() == 0) {
               AlertUtils.alert_warning("请选择json");
           }

           try {
               JSONParser parser = new JSONParser();
               JSONObject root = (JSONObject) parser.parse(json_str.getText());
               json_view.setRoot(parseJSON("root_object", root));
               json_view.setId("json_view");
               json_view.setShowRoot(false);
           } catch (ParseException e) {
               e.printStackTrace();
           }

        });
    }

    public void choose_file() {
        Stage stage = new Stage();
        FileChooser fc = new FileChooser();
        fc.setTitle("单选文件");
        fc.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("json文件", "*.json")
        );
        File file = fc.showOpenDialog(stage);
        if (file == null) {
            return;
        }
        path.setText(file.getPath());
        try {
            JSONParser parser = new JSONParser();
            JSONObject root = (JSONObject) parser.parse(new FileReader(new File(path.getText()), StandardCharsets.UTF_8));
            obj.setValue(root);
            json_str.setText(JSONObject.toJSONString(root));
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }


    @SuppressWarnings("unchecked")
    private static TreeItem<String> parseJSON(String name, Object json) {
        TreeItem<String> item = new TreeItem<>();
        item.setExpanded(true);
        if (json instanceof JSONObject object) {
            item.setValue(name);
            ((Set<Map.Entry>) object.entrySet()).forEach(entry -> {
                String childName = (String) entry.getKey();
                Object childJson = entry.getValue();
                TreeItem<String> child = parseJSON(childName, childJson);
                child.setExpanded(true);
                item.getChildren().add(child);
            });
        } else if (json instanceof JSONArray array) {
            item.setValue(name);
            for (int i = 0; i < array.size(); i++) {
                String childName = String.valueOf(i);
                Object childJson = array.get(i);
                TreeItem<String> child = parseJSON(childName, childJson);
                child.setExpanded(true);
                item.getChildren().add(child);
            }
        } else {
            item.setValue(name + " : " + json);
        }
        return item;
    }
}